// packageF/sachertorte/sachertorteSearch/sachertorteSearch.js
let app = getApp();
let location = require("../../../mybehaviors/location/location");
import util from "../../../utils/util";
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    search:'',
    screenShow:false,
    goodsList:[],
    cakeType:[
      {
        type:'',
        text:'全部'
      },
      {
        type:1,
        text:'4-5人食'
      },
      {
        type:2,
        text:'6-9人'
      },
      {
        type:3,
        text:'10-12人'
      },
      {
        type:4,
        text:'12人以上'
      }
    ],
    getBrand: [
    ],
    query: {
      page:1,
      city:'',
      order_field:'',
      order_by:'',
      cake_type:'',
      cake_price_max:'',
      cake_price_min: '',
      snacks_price_max:"",
      snacks_price_min: "",
    },
    totalPage:0,
    isLoadMore: true,
    brandsId:'',
    categorysId:'',
    keyword:'',
    priceSnacks:[
     {
      type: ["", ""],
      text:'全部',
     },
     {
      type: [20,99],
      text:'20-99',
     },
     {
      type: [100,199],
      text:'100-199',
     },
     {
      type: [199,''],
      text:'199以上',
     }
    ], 
    cakePriceArr:[
      {
        type: ['',''],
        text:'全部',
       },
       {
        type: [100,200],
        text:'100-200',
       },
       {
        type: [200,300],
        text:'200-300',
       }
    ],
    categorys: [],
    indexType:0, //尺寸选择
    storageName: "sachertorte", // 蛋糕显示历史搜索记录
    showHistory:false,
    total_page:0,
    background_color:'#ffc11e',
    store_id:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.city) {
      this.setData({
        'query.city': options.city,
      })
    }
    if(options.store_id){
      this.setData({
        store_id:options.store_id
      })
    }
    wx.setNavigationBarTitle({
      title: options.store_id?'门店商品':'搜索',
    })
  },
  searchBlur(){
    this.setData({
      showHistory:false
    })
  },
  hidebox(){
    this.setData({
      screenShow: false
    })
    let searchHistoryList = wx.getStorageSync(this.data.storageName);
    if (searchHistoryList.length > 0) {
      this.showHistory = true;
      this.setData({
        showHistory:true
      })
    }
    console.log(searchHistoryList)
  },
  goodsByList() {
    wx.showLoading({
      title: '加载中',
    })
    let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.goods.goods.getGoodsList");
    urlStr += `&search[brand_id]=${this.data.brandsId}`;
    urlStr += `&search[category]=${this.data.categorysId}`;
    urlStr += `&search[keyword]=${this.data.keyword}`;
    if(this.data.store_id){
      urlStr += `&yz_supply_cake_store_id=${this.data.store_id}`
    }
    app._getNetWork({
      url: urlStr,
      data:this.data.query,
      success:  (resdata) => {
        let res = resdata.data;
        wx.hideLoading();
        wx.hideNavigationBarLoading();//隐藏导航条加载动画
        //停止下拉刷新
        wx.stopPullDownRefresh();
        if (res.result == 1) {
          this.data.totalPage = res.data.last_page;
          if (!this.data.totalPage) {
            this.data.totalPage = 0;
          }
          this.setData({
            goodsList: res.data.data,
          })
        } else {
          this.data.page = this.data.page - 1;
          this.isLoadMore = false;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
   //获取更多数据
  getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.query.page >= this.data.totalPage) {
      return;
    } else {
      this.data.query.page = this.data.query.page + 1;
      let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.goods.goods.getGoodsList");
      urlStr += `&search[brand_id]=${this.data.brandsId}`;
      urlStr += `&search[category]=${this.data.categorysId}`;
      urlStr += `&search[keyword]=${this.data.keyword}`;
      if(this.data.store_id){
        urlStr += `&yz_supply_cake_store_id=${this.data.store_id}`
      }
      app._getNetWork({
        url: urlStr,
        data: this.data.query,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data.data;
          if (res.result == 1) {
            this.data.isLoadMore = true;
            this.setData({
              goodsList : this.data.goodsList.concat(list),
            })
            console.log(this.data.goodsList,list)
          } else {
            this.data.query.page = this.data.query.page - 1;
            this.data.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  screenClick(event) {  //筛选完成
    let {brandValue,cakeValue,categoryValue,priceValue,cakePirceValue} = event.detail;
    this.setData({
      screenShow: false,
      isLoadMore: true,
      brandsId:brandValue,
      categorysId:categoryValue,
      'query.cake_type': cakeValue,
      'query.page':1,
      'query.cake_price_min': cakePirceValue[0],
      'query.cake_price_max':cakePirceValue[1],
      'query.snacks_price_min': priceValue[0],
      'query.snacks_price_max':  priceValue[1],
    })
    this.goodsByList();
  },
  popularity() { //选择人气
    this.setData({
      'query.order_field': 'popularity',
      'query.order_by':'',
      'query.page':1,
      isLoadMore:true
    })
    this.goodsByList();
  },
  salesClick(event) {
    let sort = event.currentTarget.dataset.sort;
    let sortValue = 'asc';
    this.sortSwicth(sort,sortValue,'show_sales'); //处理判断倒序，正序
  },
  sortSwicth(sort,sortValue,field) {
    switch(sort) {
      case 'asc':
         sortValue = 'desc';
         break;
      case 'desc':
         sortValue = 'asc';
         break;
    }
    this.setData({
      'query.page':1,
      'query.order_by': sortValue,
      'query.order_field': field,
      isLoadMore:true
    })
    this.goodsByList();
  },
  searchOn(event) { //搜索
    console.log(typeof(event.detail))
    if(typeof(event.detail) != 'object') {
      this.setData({
        keyword:event.detail
      })
      this.selectComponent("#search_history").appendKeywords(this.data.keyword);
    }else{
      this.setData({
        keyword:''
      })
    }
    
    if (this.timer) clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      util.debounce(this.goodsByList());
    }, 500);
  },
  priceClick(event) { //选择价格
    let sort = event.currentTarget.dataset.sort;
    let sortValue = 'asc';
    this.sortSwicth(sort,sortValue,'price'); //处理判断倒序，正序
  },
  brandClick(event) { //品牌
    let id = event.detail.id;
    this.setData({
      ['search.brand_id']: id
    })
  },
  screeningPopup() {
    this.setData({ screenShow: true });
  },
  getBrandsData() {
    let query = {
      city: this.data.query.city
    }
    let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.goods.goods.getBrand");
    app._getNetWork({
      url: urlStr,
      data:query,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setData({
            getBrand:res.data
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  categorysList() { //分类数据
    let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.index.index.getCategorys");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          this.setData({
            categorys: res.data
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    try {
      this._getLocation((mapdata, e) => { //获取定位的城市，拿到定位的信息
        let city = mapdata.address_component.city;
        if(!this.data.query.city) {
          this.setData({
            'query.city':city
          });
        }
        //定位后调用首页接口和推荐列表接口
        this.categorysList();
        this.goodsByList();
        this.getBrandsData();
      });
    } catch (e) {
      console.log(e);
      this.categorysList();
      this.goodsByList();
      this.getBrandsData();
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let basic_info = wx.getStorageSync('yz_basic_info');
    this.setData({
      background_color:basic_info.theme_color
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})